package main

import (
	"fmt"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

var DB *sql.DB

func init() {
	database, err := sql.Open("mysql", "admin:admin123@tcp(192.168.3.103:3306)/Golang_week10")
	if err != nil {
		fmt.Println("连接数据库失败:", err)
		return
	}
	DB = database
}

type Person struct {
	ID int `db:"user_id"`
	Username sql.NullString `db:"username"`
	Gender sql.NullString `db:"gender"`
	Email sql.NullString `db:"email"`
}

func query() {
	rows, err := DB.Query("select * from person where user_id > ?", 1)
	defer func() {
		if rows != nil {
			rows.Close()
		}
	}()
	if err != nil {
		fmt.Println("Query 查询 ERROR:", err)
		return
	}
	var person = new(Person)
	for rows.Next() {
		if err = rows.Scan(&person.ID, &person.Username, &person.Gender, &person.Email); err != nil {
			fmt.Println("Scan Failed:", err)
			return
		}
		fmt.Println(person)}
}

func main() {
	query()
}